//
//  SocketRequest.m
//  TengyunStation
//
//  Created by Johnny on 15/8/21.
//  Copyright (c) 2015年 xingrong. All rights reserved.
//

#import "SocketRequest.h"
#import "Singleton.h"
#define SocketTimeOut       15
#define SocketHeadTag       100
#define SocketContentTag    101

@implementation SocketRequest

- (id)initWithSocketRequestDelegate:(id<SocketRequestDelegate>)delegate {
    self = [super init];
    if (self) {
        self.delegate = delegate;
        _socketQueue = [NSMutableArray arrayWithCapacity:1];
    }
    return self;
}

- (void)addSocketData:(NSData *)data SocketTag:(NSInteger)tag {
    for (GCDAsyncSocket *socket in _socketQueue) {
        if (socket.socketTag == tag) {
            return;
        }
    }
    [self addMultipleSocketData:data SocketTag:tag];
}

- (void)addMultipleSocketData:(NSData *)data SocketTag:(NSInteger)tag {
    NSData *socketData = [SocketMethod doubleHexEncryptMessageData:data];
    GCDAsyncSocket *socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue() SocketData:socketData Tag:(int)tag];
    UInt16 port = [[Singleton shareInstance].cityModel.preSystemPort intValue];
    [socket connectToHost:[Singleton shareInstance].cityModel.preSystemIP onPort:port withTimeout:SocketTimeOut error:nil];
    [_socketQueue addObject:socket];
}

- (BOOL)isDisconnectAll {
    if (_socketQueue.count > 0) {
        return NO;
    } else {
        return YES;
    }
}

#pragma mark GCDAsyncSocketDelegate
- (void)socket:(GCDAsyncSocket *)sender didConnectToHost:(NSString *)host port:(UInt16)port {
    [sender writeData:sender.socketData withTimeout:SocketTimeOut tag:0];
}

- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag {
    [sock readDataToLength:4 withTimeout:SocketTimeOut tag:SocketHeadTag];
}

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
    if (tag == SocketHeadTag) {
        NSInteger length = [SocketMethod getLengthWithData:data];
        [sock readDataToLength:length withTimeout:SocketTimeOut tag:SocketContentTag];
    } else if (tag == SocketContentTag) {
        if ([_socketQueue containsObject:sock]) {
            [_socketQueue removeObject:sock];
            NSData *firstData = [SocketMethod messageDataDecryptHexData:data];
            //应答码
            NSData *responseCodeData = [firstData subdataWithRange:NSMakeRange(0, 5)];
            NSString *responseCode = [SocketMethod stringData:responseCodeData];
            //应答信息
            NSData *responseMsgData = [firstData subdataWithRange:NSMakeRange(5, 64)];
            NSString *responseMsg = [SocketMethod stringData:responseMsgData];
            //内容
            DLog(@"socketTag:%d,code:%@,msg:%@",sock.socketTag,responseCode,responseMsg);
            NSData *contentData = [firstData subdataWithRange:NSMakeRange(69, (firstData.length - 69))];
            if ([_delegate respondsToSelector:@selector(socket:Code:Msg:Data:)]) {
                [_delegate socket:sock Code:responseCode Msg:responseMsg Data:contentData];
            }
        }
        sock.delegate = nil;
        [sock disconnect];
    }
}

- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err {
    if ([_socketQueue containsObject:sock]) {
        [_socketQueue removeObject:sock];
        if ([_delegate respondsToSelector:@selector(socket:Msg:)]) {
            NSString *msg = @"网络请求失败，请检查您的网络！";
            if (err.code == 3) {
//                msg = @"服务器异常";
            }
            DLog(@"socketTag:%d,errorcode:%ld",sock.socketTag,(long)err.code);
            [_delegate socket:sock Msg:msg];
        }
    }
    sock.delegate = nil;
    [sock disconnect];
}

@end
